package com.mlx.mylogin.impl;

import com.mlx.mylogin.base.Configuration;
import com.mlx.mylogin.base.LoginException;
import com.mlx.mylogin.inter.AbstractLoginManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class SessionLoginManager extends AbstractLoginManager {

    public SessionLoginManager(Configuration configuration) {
        super(configuration);
    }

    @Override
    protected String generateToken(HttpServletRequest request, Object user) {
        return configuration.getTokenKey();
    }

    @Override
    protected void saveToken(HttpServletRequest request, HttpServletResponse response, Object user, String token) {
        request.getSession().setAttribute(token, user);
    }


    @Override
    protected Object parseToken(HttpServletRequest request, String token) {
        HttpSession session = request.getSession();
        Object user = session.getAttribute(token);
        if (user == null){
            throw new LoginException("未登录");
        }
        return user;
    }

}
